//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package impl

import (
	"bytes"
	"strings"

	"atomgit.com/openlinksaas/search-proxy/core"
	"github.com/antchfx/htmlquery"
)

type RubygemsParser struct{}

func (parser *RubygemsParser) MatchUrl(url string) bool {
	return strings.HasPrefix(url, "https://rubygems.org/search")
}

func (parser *RubygemsParser) Parse(url string) ([]*core.SearchEntry, error) {
	body, err := GetPage(url)
	if err != nil {
		return nil, err
	}

	doc, err := htmlquery.Parse(bytes.NewBuffer(body))
	if err != nil {
		return nil, err
	}

	retList := []*core.SearchEntry{}
	linkElList := htmlquery.Find(doc, "//a[@class='gems__gem']")
	for _, linkEl := range linkElList {
		summary := ""
		descEl := htmlquery.FindOne(linkEl, "/span[@class='gems__gem__info']/p[@class='gems__gem__desc t-text']")
		if descEl != nil {
			summary = htmlquery.InnerText(descEl)
		}
		titleEl := htmlquery.FindOne(linkEl, "/span[@class='gems__gem__info']/h2[@class='gems__gem__name']")
		if titleEl != nil {
			retList = append(retList, &core.SearchEntry{
				Title:   htmlquery.InnerText(titleEl),
				Url:     "https://rubygems.org" + htmlquery.SelectAttr(linkEl, "href"),
				Summary: summary,
			})
		}
	}
	return retList, nil
}
